package com.ehome.plugin

import com.android.build.api.artifact.ScopedArtifact
import com.android.build.api.dsl.CommonExtension
import com.android.build.api.variant.ApplicationAndroidComponentsExtension
import com.android.build.api.variant.DslExtension
import com.android.build.api.variant.ScopedArtifacts
import com.android.build.api.variant.VariantExtensionConfig
import com.android.build.gradle.AppPlugin
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.ExtensionAware
import org.gradle.kotlin.dsl.register

class EHomeApmPlugin : Plugin<Project> {
    private val TAG = EHomeApmPlugin::class.simpleName

    override fun apply(project: Project) {
        println("apply $TAG ...")

        project.plugins.withType(AppPlugin::class.java) {

            val androidComponents = project.extensions.getByType(ApplicationAndroidComponentsExtension::class.java)

            androidComponents.registerExtension(
                DslExtension.Builder("apm")
                    .extendProjectWith(EHomeApmExtension::class.java)
                    .build()
            ) { config: VariantExtensionConfig<*> ->
                project.objects.newInstance(
                    VariantDslExtension::class.java,
                    config
                )
            }

            val android = project.extensions.getByType(CommonExtension::class.java)
            androidComponents.onVariants { variant ->

                val taskProvider = project.tasks.register<EHomeApmTask>("${variant.name}ModifyClasses") {
                    variantExtension.set(variant.getExtension(VariantDslExtension::class.java))
                    apmExtension.set((android as ExtensionAware).extensions.getByType(EHomeApmExtension::class.java))
                }

                variant.artifacts.forScope(ScopedArtifacts.Scope.PROJECT)
                    .use(taskProvider)
                    .toTransform(
                        ScopedArtifact.CLASSES,
                        EHomeApmTask::allJars,
                        EHomeApmTask::allDirectories,
                        EHomeApmTask::output
                    )
            }
        }
    }
}